import { Component, ViewChild, Injector, Output, EventEmitter, ViewEncapsulation, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import {
  CityServiceProxy,
  ListResultDtoOfUserListDto,
  AgentServiceProxy,
  ApplyUpdateToAgentRequestDto,
  UpgradeUserToAgentRequestDto,
  ListResultDtoOfCityOutDto,
  CityOutDto,
  UserServiceProxy,
  UserListDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'agent-add',
  templateUrl: 'agent-add.component.html',
  styleUrls: ['agent-add.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AgentAddComponent extends AppComponentBase {
  @ViewChild('createAgentModal') modal: ModalDirective;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  @ViewChild('userSelectModal') public userSelectModal: ModalDirective;

  active: boolean = false;
  saving: boolean = false;
  provinces: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  cities: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  districts: ListResultDtoOfCityOutDto = new ListResultDtoOfCityOutDto();
  agentApply: UpgradeUserToAgentRequestDto = new UpgradeUserToAgentRequestDto();
  nullObj = new CityOutDto();
  selectedUserName: string = '';
  userList: ListResultDtoOfUserListDto = new ListResultDtoOfUserListDto();
  downloadUrl: string = AppConsts.remoteServiceBaseUrl + '/file/download';
  constructor(
    injector: Injector,
    private _agentService: AgentServiceProxy,
    private _cityService: CityServiceProxy,
    private _userService: UserServiceProxy
  ) {
    super(injector);
    this.nullObj.id = undefined;
    this.nullObj.name = '--请选择--';
    this.provinces.items = [this.nullObj];
    this.cities.items = [this.nullObj];
    this.districts.items = [this.nullObj];
  }

  show(): void {
    this.active = true;
    this.getCities();
    this.agentApply = new UpgradeUserToAgentRequestDto();
    this.agentApply.userType = "";
    this.modal.show();
  }

  getCities(id?: number): void {
    this._cityService.getByParentId(id)
      .subscribe((result: ListResultDtoOfCityOutDto) => {
        if (!id) {
          this.provinces = result;
          this.provinces.items.unshift(this.nullObj);
        } else {
          if (id.toString().length === 2) {
            this.cities = result;
            this.cities.items.unshift(this.nullObj);
          } else {
            this.districts = result;
            this.districts.items.unshift(this.nullObj);
          }
        }
      });
  }

  save(): void {
    this.saving = true;
    this._agentService.upgradeUserToAgentAsync(this.agentApply)
      .finally(() => { this.saving = false; })
      .subscribe(() => {
        this.notify.info('保存成功!等待用户确认!');
        this.close();
        this.modalSave.emit(null);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }

  provinceChange(event: any): void {
    this.agentApply.provinceId = event;
    this.agentApply.cityId = undefined;
    this.agentApply.districtId = undefined;
    this.districts.items = [this.nullObj];
    this.getCities(this.agentApply.provinceId);
  }
  cityChange(event: any): void {
    this.agentApply.cityId = event;
    this.agentApply.districtId = undefined;
    this.getCities(this.agentApply.cityId);
  }


  getUsers(): void {
    this._userService.getUsers().subscribe((result: ListResultDtoOfUserListDto) => {
      this.userList = result;
      this.userSelectModal.show();
    });
  }

  showSelectUser(): void {
    this.getUsers();
  }

  selectedUser(user: UserListDto): void {
    this.selectedUserName = user.name + '/' + user.phoneNumber;
    this.agentApply.userId = user.id;
    this.userSelectModal.hide();
  }
}
